<template>
  <a-modal :width="1200" v-model:visible="showDetail" :title="`编辑交货单-${detailInfo.billNo}`" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="purchase-order-detail">
      <div class="header">
        <p class="title">基础信息</p>
      </div>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">创建人：</p>
            <p class="val">{{ detailInfo.createUname }}</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">创建时间：</p>
            <p class="val">{{ $setTime(detailInfo.gmtCreate) }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row class="detail-item">
        <a-col :span="8">
          <div class="flex">
            <p class="label">收货仓库：</p>
            <p class="val">{{ detailInfo.warehouseName }}（{{ detailInfo.warehouseCode }}）</p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="flex">
            <p class="label">供应商：</p>
            <p class="val">{{ detailInfo.supplierName }}（{{ detailInfo.supplierCode }}）</p>
          </div>
        </a-col>
      </a-row>
      <div class="purchase-detail-order">
        <a-table class="table-two-line show-border-table" ref="tableRef" :data="detailInfo.billItems" :scroll="{ x: '100%', y: '100%' }" size="mini" :pagination="false">
          <template #columns>
            <a-table-column data-index="purchaseNo" title="采购单" :width="130" fixed="left">
              <template #cell="{ record }">
                <p class="highlight">{{ record.purchaseNo }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="img" title="图片" :width="60" fixed="left">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="50" height="50" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column data-index="sku" title="SKU" :width="140" fixed="left">
              <template #cell="{ record }">
                <p>{{ record.sku }}</p>
                <p>{{ getProductSpecs(record) }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="price" title="单价" :width="120">
              <template #cell="{ record }">
                <p>材质：￥{{ record.materialPrice }}</p>
                <p>产品：￥{{ record.productPrice }}</p>
                <p>工费：￥{{ record.laborPrice }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="purchaseAmt" title="采购数量" :width="70" />
            <a-table-column data-index="purchaseDeliveryStayAmt" title="未交货数" :width="85">
              <template #title>
                <a-popover content="未交货数=采购数量-已签收数-已交货未签收数-截单数">
                  <p>
                    <span>未交货数</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
            </a-table-column>
            <a-table-column data-index="deliveryAmt" title="本次交货数" :width="110">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>本次交货数=未交货数+（未交货数*0.3向上取整），</p>
                    <p>{{ `未交货数*0.3如果<=2则默认为3，也就是说供应商可以多发3件以上的货。` }}</p>
                  </template>
                  <p>
                    <span>本次交货数</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-input-number :precision="0" :min="0" v-model="record.deliveryAmt" style="width: 80px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'deliveryAmt')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column data-index="materialWeight" title="交货材质重量(g)" :width="120">
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-input-number :precision="0" :min="0" v-model="record.materialWeight" style="width: 80px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'materialWeight')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column data-index="otherAmount" title="其他费用" :width="110">
              <template #title>
                <a-popover content="本次交货产生其他费用">
                  <p>
                    <span>其他费用</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-input-number :precision="2" :min="0" v-model="record.otherAmount" style="width: 80px" placeholder="" hide-button />
                  <icon-double-down v-if="rowIndex < detailInfo.billItems.length - 1" class="edit-icon" @click="setGlobal(record, 'otherAmount')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column title="材质金额" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>材质金额：</p>
                    <p>签收前=材质单价*交货材质重量</p>
                    <p>签收后=材质单价*实收材质重量</p>
                  </template>
                  <p>
                    <span>材质金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ (Number(record.materialWeight || 0) * Number(record.materialPrice || 0)).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="产品金额" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>产品金额：</p>
                    <p>签收前=产品单价*交货数量</p>
                    <p>签收后=产品单价*实际签收数量</p>
                  </template>
                  <p>
                    <span>产品金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ (Number(record.deliveryAmt || 0) * Number(record.productPrice || 0)).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="工费" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>工费金额：</p>
                    <p>签收前=工费单价*交货数量</p>
                    <p>签收后=工费单价*实际签收数量</p>
                  </template>
                  <p>
                    <span>工费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ (Number(record.deliveryAmt || 0) * Number(record.laborPrice || 0)).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="合计金额" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>合计金额=材质金额+产品金额+工费+其他费用</p>
                  </template>
                  <p>
                    <span>合计金额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ getTotalAmount(record).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="税金" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>税金=税率*合计金额</p>
                  </template>
                  <p>
                    <span>税金</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ ((getTotalAmount(record) * Number(record.rate || 0)) / 100).toFixed(2) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="单件货值" :width="90">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>单件货值(含税)=（合计金额-税金）/实际签收数量</p>
                    <p>单件货值(不含税)=合计金额/实际签收数量</p>
                  </template>
                  <p>
                    <span>单件货值</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <span>￥{{ getTotalValue(record).toFixed(2) }}</span>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button class="gray-outline" @click="closedDialog">取消</a-button>
        <a-button type="primary" @click="submitData(currentItem.status)" :loading="submitLoading">保存</a-button>
        <a-button type="primary" @click="submitData(10)" :loading="submitLoading">保存并提交</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { getDeliveryInfo, updatePurchaseDelivery } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import { Message } from '@arco-design/web-vue'
  import { cloneDeep } from 'lodash-es'
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })

  const showDetail = ref(props.isShow)
  const detailInfo = ref<any>({})
  const submitLoading = ref(false)

  // 关闭
  function closedDialog() {
    showDetail.value = false
    emit('closed')
  }

  // 获取详情
  async function getDetail() {
    if (!props.currentItem.id) return
    const res: any = await getDeliveryInfo({ id: props.currentItem.id })
    detailInfo.value = res?.data || {}
    detailInfo.value.billItems.forEach((item: any) => {
      item.materialWeight = item.materialWeight
      item.deliveryAmt = item.deliveryAmt
    })
  }
  getDetail()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }

  // 确认
  async function submitData(status: number) {
    let parmas: any = cloneDeep(detailInfo.value)
    let flag = false
    parmas.billItems = detailInfo.value.billItems.map((item: any) => {
      if (!item.deliveryAmt) {
        flag = true
      }
      return {
        billId: item.billId,
        id: item.id,
        materialWeight: item.materialWeight,
        deliveryAmt: item.deliveryAmt,
        otherAmount: item.otherAmount,
        purchaseId: item.purchaseId,
        purchaseItemId: item.purchaseItemId,
        remark: item.remark,
        settleType: item.settleType,
      }
    })
    parmas.status = status
    if (flag) {
      Message.error('本次交货数必填')
      return
    }
    submitLoading.value = true
    const res: any = await updatePurchaseDelivery(parmas)
    submitLoading.value = false
    if (res) {
      Message.success('保存成功')
      emit('success')
      closedDialog()
    }
  }
  // 获取合计金额
  function getTotalAmount(row: any) {
    let materialAmount = Number(row.materialWeight || 0) * Number(row.materialPrice || 0)
    let productAmount = Number(row.deliveryAmt || 0) * Number(row.productPrice || 0)
    let laborAmount = Number(row.deliveryAmt || 0) * Number(row.laborPrice || 0)
    let otherAmount = Number(row.otherAmount || 0)
    return materialAmount + productAmount + laborAmount + otherAmount
  }
  // 获取单件货值
  function getTotalValue(row: any) {
    let totalAmount = getTotalAmount(row)
    let rateAmount = row.priceType === 0 ? 0 : (totalAmount * Number(row.rate || 0)) / 100
    return row.deliveryAmt ? (totalAmount - rateAmount) / row.deliveryAmt : 0
  }
  //设置全局
  async function setGlobal(item: any, key: string) {
    detailInfo.value.billItems.forEach((el: any) => {
      el[key] = item[key]
    })
  }
</script>

<style lang="less" scoped>
  .purchase-order-detail {
    height: calc(84vh - 160px);
    display: flex;
    flex-direction: column;
    .purchase-detail-order {
      margin-top: 20px;
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .edit-icon {
      font-size: 16px;
      margin-left: 5px;
      cursor: pointer;
    }
    .header {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 10px;
      border-left: 3px solid rgba(var(--primary-6), 0.5);
      padding-left: 10px;
      .title {
        margin-right: 30px;
        width: 90px;
      }
    }
    .detail-item {
      margin-bottom: 5px;
      .label {
        width: 120px;
        text-align: right;
      }
      .val {
        color: #666;
      }
      .info {
        font-size: 12px;
        color: #999;
      }
    }
  }
</style>
